package com.iting.mongo;

import com.iting.bean.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("/mongo")
public class MongoController {

	@Autowired
	private MongoTemplate mongoTemplate;

	@RequestMapping("/findOne")
	public Student mongoQueryOne(@RequestParam(value = "name",required = true) String name){
		Query query = new Query();

		Criteria criteria = Criteria.where("name").is(name);
		query.addCriteria(criteria);
		Student one = mongoTemplate.findOne(query, Student.class);
		return one;
	}

	@RequestMapping("/findAll")
	public List<Student> mongoQueryMany(){
		return mongoTemplate.findAll(Student.class);
	}

	@RequestMapping("/insert")
	public String mongoInsert(){
		String name = UUID.randomUUID().toString().replaceAll("-","").substring(0,10);
		Integer age = new Random().nextInt(100);
		Student student = new Student(name,age);
		student.addAlias("a");
		student.addAlias("1");
		student.addAlias("b");
		student.addAlias("2");
		student.addAlias("0");
		mongoTemplate.insert(student);
		return "插入一条数据成功";
	}
}
